<template>
  <el-scrollbar>
    <el-menu :default-active="defaultActive" :collapse="isCollapse" :unique-opened="uniqueOpened"
      :collapse-transition="false" background-color="transparent" mode="vertical" router>
      <menu-item v-for="menu in filteredRoutes" :key="menu.path" :menu="menu"></menu-item>
    </el-menu>
  </el-scrollbar>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { storeToRefs } from "pinia";
import MenuItem from "./MenuItem.vue";

const routerStore = useStore.routerStore();
const appStore = useStore.appStore();
const userStore = useStore.userStore();
const { sidebarOpened, theme }: any = storeToRefs(appStore);

const route = useRoute();

// 去掉任意语言前缀，统一用“无前缀”的路径作为选中键
const stripAnyLocalePrefix = (p: string) => {
  return (p || "/").replace(/^\/(en-US|zh-CN|zh-HK)(?=\/|$)/, "") || "/";
};

const defaultActive = computed(() => {
  // const currentPath = route.path || "/";
  // return stripAnyLocalePrefix(currentPath);
  const currentPath = stripAnyLocalePrefix(route.path || "/");
  const findByPath = (routes: any[], p: string): any | null => {
    for (const r of routes) {
      if (r.path === p) return r;
      if (r.children?.length) {
        const hit = findByPath(r.children, p);
        if (hit) return hit;
      }
    }
    return null;
  };
  const matched = findByPath(routerStore.routes, currentPath);
  const active = stripAnyLocalePrefix(matched?.activeMenu || currentPath);

  // 可保留此行用于调试
  console.log("path:", currentPath, "activeMenu:", matched?.activeMenu);

  return active;
});

const isCollapse = computed(() => {
  return !sidebarOpened.value;
});

const uniqueOpened = computed(() => {
  return theme.value.uniqueOpened;
});

// 递归过滤隐藏菜单和需要 bizUserId 的菜单
const deepFilterRoutes = (routes: any[] = []): any[] => {
  return routes.reduce((acc: any[], item: any) => {
    // 过滤隐藏菜单
    if (item?.meta?.isHidden) return acc;
    // 过滤需要 bizUserId 但用户没有 bizUserId 的菜单
    if (item?.meta?.requiresBizUserId && !userStore.user.bizUserId) return acc;
    const children = deepFilterRoutes(item?.children || []);
    acc.push({ ...item, children });
    return acc;
  }, []);
};

const filteredRoutes = computed(() => deepFilterRoutes(routerStore.routes));
</script>
